Page({
  data: {
    points: [],
    timer: null,
    time: 0
  },

  onLoad() {
    this.initCanvas();
  },

  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  initCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#heartRateCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas大小
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);

        // 初始化点数组
        const points = [];
        for (let i = 0; i < res[0].width; i++) {
          points.push({
            x: i,
            y: res[0].height / 2
          });
        }
        this.setData({ points });

        // 开始动画
        this.startAnimation(ctx, canvas.width / dpr, canvas.height / dpr);
      });
  },

  // 生成30到40之间的随机数
  getRandomNumber() {
    return 30 + Math.random() * 10;
  },
  getRandomNumber2() {
    return 20 + Math.random() * 10;
  },

  // 生成波形
  generateWave(time) {
    // 基础波形
    const baseWave = Math.sin(time * 0.24) * 40;
    // 添加随机波动
    const randomWave = Math.sin(time * 0.44) * 25;
    return baseWave + randomWave;
  },

  startAnimation(ctx, width, height) {
    const draw = () => {
      ctx.clearRect(0, 0, width, height);
      
      // 更新点的位置
      const points = this.data.points;
      points.shift();
      
      // 生成新的点
      const time = this.data.time;
      const newY = height / 2 + this.generateWave(time);
      points.push({
        x: width,
        y: newY
      });

      // 绘制波形
      ctx.beginPath();
      ctx.strokeStyle = '#00ff00';
      ctx.lineWidth = 2;
      
      points.forEach((point, index) => {
        if (index === 0) {
          ctx.moveTo(point.x, point.y);
        } else {
          ctx.lineTo(point.x, point.y);
        }
      });
      
      ctx.stroke();

      // 更新所有点的x坐标
      points.forEach(point => {
        point.x -= 2;
      });

      // 更新时间
      this.setData({ 
        points,
        time: time + 1
      });
    };

    const timer = setInterval(draw, 16);
    this.setData({ timer });
  }
});
